<?php


namespace App\Http\Controllers;


use App\Models\Log;
use \Illuminate\Http\Request;

class LogController extends Controller
{
    /**
     * 首页
     */
    public function index(Request $request){
        if ($start_time = $request->get('start_time')){
            $start_time = strtotime($start_time);
        }else{
            $start_time = 0;
        }
        if ($end_time = $request->get('end_time')){
            $end_time = strtotime($end_time);
        }else{
            $end_time = time();
        }
        $page = $request->get('page')?$request->get('page'):1;
        $total = Log::whereRaw(['create_time' => ['$gte' => $start_time, '$lte' => $end_time]])->count();
        $perPage = 25;
        $skip = ($page-1) * $perPage;
        $total_page = ceil($total/$perPage);


        $log = Log::orderBy('create_time','desc')->whereRaw(['create_time' => ['$gte' => $start_time, '$lte' => $end_time]])->skip($skip)->take($perPage)->get();
        return view('welcome')
            ->with('log',$log)
            ->with('total',$total)
            ->with('start_time',$start_time)
            ->with('end_time',$end_time)
            ->with('page',$page)
            ->with('total_page',$total_page);
    }

    /**
     * 添加日志
     * @param Request $request
     */
    public function add_log(Request $request){
        $post = $request->post();
        $insert = [
            'user_id' => (int)$post['user_id'],
            'name' => $post['name'],
            'table' => $post['table'],
            'request_url' => $post['request_url'],
            'method' => $post['method'],
            'content' => json_encode($post['set'],JSON_UNESCAPED_UNICODE),
            'create_time' => time()
        ];
        Log::create($insert);
    }
}
